package com.tehui.fragment.impl;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ali.auth.third.login.callback.LogoutCallback;
import com.alibaba.baichuan.android.trade.adapter.login.AlibcLogin;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.tehui.R;
import com.tehui.activity.LoginActivity;
import com.tehui.activity.impl.AboutActivity;
import com.tehui.activity.impl.FavoriteActivity;
import com.tehui.activity.impl.MessageActivity;
import com.tehui.activity.impl.OpinionActivity;
import com.tehui.activity.impl.ServiceActivity;
import com.tehui.fragment.BaseFragment;
import com.tehui.global.LoginMode;
import com.tehui.utils.tools.PrefUtils;
import com.tehui.utils.ui.UiUtils;
import com.tencent.tauth.Tencent;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by jasmine on 2017/2/28.
 */

public class PersonFragment extends BaseFragment {

    private        ImageView      ivIcon;
    private        TextView       tvAccount;
    private static Tencent        mTencent;
    private        ImageView      infoTop;
    private        int            loginMode;
    private        String         taokeId;
    private        String         openId;
    private        String         nick;
    private        String         avatarUrl;
    private        View           view;
    private        RequestOptions options;

    //个人页面
    @Override
    public View initView() {
        mTencent = Tencent.createInstance("1106026080", activity);
        view = View.inflate(UiUtils.getContext(), R.layout.person_layout, null);
        options = new RequestOptions().centerCrop();
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
        tvAccount = (TextView) view.findViewById(R.id.tvAccounts);//用户名
        infoTop = (ImageView) view.findViewById(R.id.infoTop);
        infoTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), MessageActivity.class));
            }
        });
    }

    private void initSetMessage() {

        taokeId = getResources().getString(R.string.taokeId);
        openId = PrefUtils.getString("openId", "");
        String city = PrefUtils.getString("city", "");
        String sex = PrefUtils.getString("sex", "");
        JSONObject jsonObject = new JSONObject();
        if (!TextUtils.isEmpty(nick)) {
            try {
                jsonObject.put("OpenId", openId);
                jsonObject.put("LoginWay", loginMode);
                jsonObject.put("NickName", nick);
                jsonObject.put("TaokeId", taokeId);
                jsonObject.put("Sex", sex);
                jsonObject.put("City", city);
                jsonObject.put("AvatarUrl", avatarUrl);
                String s = jsonObject.toString();
                OkGo.post("http://dl.21tehui.com/TkUserApi.html").tag(this).params("user", s).cacheKey
                        ("cacheKey").cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        PrefUtils.setBoolean("userMessage", true);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onResume() {

        loginMode = PrefUtils.getInt("loginMode", 0);

        nick = PrefUtils.getString("nick", "");
        avatarUrl = PrefUtils.getString("avatarUrl", "");

        tvAccount.setText(nick);
        initImage(avatarUrl);

        boolean userMessage = PrefUtils.getBoolean("userMessage", false);
        boolean isLogin = PrefUtils.getBoolean("isLogin", false);
        if (isLogin && !userMessage) {
            initSetMessage();
        }
        super.onResume();
    }

    private void initImage(String url) {
        Glide.with(UiUtils.getContext()).asBitmap().load(url).apply(options).into(new BitmapImageViewTarget
                (ivIcon) {
            @Override
            protected void setResource(Bitmap resource) {
                RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(UiUtils
                        .getContext().getResources(), resource);
                circularBitmapDrawable.setCircular(true);
                ivIcon.setImageDrawable(circularBitmapDrawable);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick({R.id.rlFavorite, R.id.rlAbout, R.id.rlService, R.id.rlOpinion})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlFavorite:
                startActivity(new Intent(UiUtils.getContext(), FavoriteActivity.class));
                break;
            case R.id.rlAbout:
                startActivity(new Intent(UiUtils.getContext(), AboutActivity.class));
                break;
            case R.id.rlService:
                startActivity(new Intent(UiUtils.getContext(), ServiceActivity.class));
                break;
            case R.id.rlOpinion:
                startActivity(new Intent(UiUtils.getContext(), OpinionActivity.class));
                break;
        }
    }

    @OnClick(R.id.logout)
    public void onClick() {
        startActivityForResult(new Intent(UiUtils.getContext(), LoginActivity.class), 0);
        PrefUtils.setBoolean("isLogin", false);
        PrefUtils.setBoolean("userMessage", false);

        switch (loginMode) {
            case LoginMode.LOGIN_DEFAULT://默认账户
                break;
            case LoginMode.LOGIN_TAOBAO://淘宝账户
                //退出淘宝
                PrefUtils.setBoolean("isLoginTaoBao", false);
                AlibcLogin alibcLogin = AlibcLogin.getInstance();
                alibcLogin.logout(activity, new LogoutCallback() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(UiUtils.getContext(), "退出登录成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        Toast.makeText(UiUtils.getContext(), "退出登录失败 " + code + msg, Toast.LENGTH_SHORT)
                                .show();
                    }
                });
                break;
            case LoginMode.LOGIN_TENCENT://腾讯账户
                mTencent.logout(UiUtils.getContext());
                Toast.makeText(UiUtils.getContext(), "退出登录成功", Toast.LENGTH_SHORT).show();
                break;
            case LoginMode.LOGIN_WECHAT://微信账户
                Toast.makeText(UiUtils.getContext(), "退出登录成功", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}
